import request from '../utils/request'

const EXPIRED = 3 * 24 * 3600 * 1000 //3天毫秒跨度

export default async function(){
    // 首先从缓存中取 看有没有记录的openid
    let {openid,appid,expired} = wx.getStorageSync('openid')

    if(openid && expired >Date.now()){
        return {
            openid,appid
        }
    }
    //如果缓存中没有，就从云函数获取
    // const {result} = await wx.cloud.callFunction({
    //     name:'login'
    // })

    const {result} = await wx.cloud.callFunction({
        name:'farm',
        data:{
            $url:'login'
        }
    })

    openid = result.openid
    appid = result.appid

    console.log(result);

    // 获取微信小程序的openid存进user里面
    // try {
    //     await request('/user/', {
    //         openid
    //     }, 'POST')
    // }catch(e)  {
    //     console.log(e)
    // }
    

    //往小程序的本地存储中存储数据
    wx.setStorageSync('openid', {
        openid,
        appid,
        expired:Date.now() + EXPIRED
    })

    return {
        openid,appid
    }
}